package com.zw.transition.services;

import com.zw.transition.common.JsonResult;
import com.zw.transition.entity.*;
import com.zw.transition.mapper.AssemblyMapper;
import com.zw.transition.util.BeanUtil;
import com.zw.transition.util.ServletUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @Description: 派工单转序 服务层
 * @Author: China.wsg
 * @Date: 2021/05/13 09:11
 */
@Service
@SuppressWarnings("all")
public class AssemblyService {

    @Autowired
    private AssemblyMapper assemblyMapper;

    /**
     * 查询 清单
     */
    public AssemblySheet findSheet(String code) {
        QrParse parse = getQrParse(code);
        if (parse == null) return null;
        AssemblySheet sheet = assemblyMapper.findSheet(parse);
        return sheet;
    }

    /**
     * 申请质检列表
     */
    public List<AssemblyRoute> findApplyList(String code) {
        QrParse parse = getQrParse(code);
        if (parse == null) return null;
        List<AssemblyRoute> routes = assemblyMapper.findApplyList(parse);
        return routes;
    }

    /**
     * 完成的质检列表
     */
    public List<AssemblyRoute> findCompleteApplyList1(String code) {
        QrParse parse = getQrParse(code);
        if (parse == null) {
            return null;
        }
        List<AssemblyRoute> routes = assemblyMapper.findCompleteApplyList1(parse);
        return routes;
    }

    /**
     * 质检列表
     */
    public List<AssemblyModel> findCheckList(String code) {
        QrParse parse = getQrParse(code);
        if (parse == null) return null;
        return assemblyMapper.findCheckList(parse);
    }

    /**
     * 完成的质检列表
     */
    public List<AssemblyRoute> findCompleteApplyList2(String code) {
        QrParse parse = getQrParse(code);
        if (parse == null) {
            return null;
        }
        List<AssemblyRoute> routes = assemblyMapper.findCompleteApplyList2(parse);
        return routes;
    }

    /**
     * 转序接收列表
     */
    public List<AssemblyModel> findRecList(String code) {
        QrParse parse = getQrParse(code);
        if (parse == null) return null;
        List<AssemblyModel> routes = assemblyMapper.findRecList(parse);
        return routes;
    }

    /**
     * 完成的申请质检列表
     */
    public List<AssemblyRoute> findCompleteApplyList(String code) {
        QrParse parse = getQrParse(code);
        if (parse == null) {
            return null;
        }
        List<AssemblyRoute> routes = assemblyMapper.findCompleteApplyList(parse);
        return routes;
    }

    /**
     * 申请质检
     */
    @Transactional(rollbackFor = Exception.class)
    public JsonResult apply(AssemblyRoute route) {
        JsonResult jsonResult = new JsonResult();
        // 修改路线表数量 可申请数减少， 已申请数增加
        int num = assemblyMapper.updateRouteApply(route);
        AssemblyRoute asseRoute = assemblyMapper.getAssemblyRouteByPrimaryKey(route.getId());
        if (num == 0) {
            jsonResult.setType(JsonResult.ResultType.ERROR);
            jsonResult.setMsg("申请失败，因申请数量超过可申请数量,可申请数量为" + asseRoute.getMayApplyNum() + "个零件！");
        } else {
            // 工序未开始转为执行中
            if (asseRoute.getStatus().compareTo(1) == 0) {
                asseRoute.setStatus(2);
                assemblyMapper.updateAsseRouteStatusExe(asseRoute);
            }
            // 生成转序单(装配转序单表)
            AssemblyTransSheet trans = new AssemblyTransSheet();
            trans.setRouteId(route.getId());
            trans.setNum(route.getApplyNum());
            User u = (User) ServletUtils.getSession().getAttribute("user");
            trans.setApplyCode(u.getAccount());
            trans.setApplyName(u.getName());
            trans.setApplyTime(new Date());
            if (u.getBranch() != null) {
                trans.setApplyDept(u.getBranch());
            }
            trans.setIsDel(0);
            assemblyMapper.addTrans(trans);
            //生成装配质检表
            AssemblyTransCheck transCheck = new AssemblyTransCheck();
            transCheck.setTransId(trans.getId());
            transCheck.setStatus(1);
            transCheck.setYield(0);
            assemblyMapper.addTransCheck(transCheck);
            jsonResult.setType(JsonResult.ResultType.SUCCESS);
            jsonResult.setMsg("申请成功！");
        }
        return jsonResult;
    }

    /**
     * 历史申请
     */
    public List<AssemblyModel> findHisApplyList() {
        User u = (User) ServletUtils.getSession().getAttribute("user");
        return assemblyMapper.findHisApplyList(u.getAccount());
    }

    /**
     * 转序主单
     */
    public AssemblyTransSheet getTransSheet(Integer id) {
        return assemblyMapper.getTransSheet(id);
    }

    /**
     * 转序主单
     */
    public AssemblyTransCheck getTransSheetCheck(Integer id) {
        return assemblyMapper.getTransSheetCheck(id);
    }

    /**
     * 取消申请质检
     */
    @Transactional(rollbackFor = Exception.class)
    public int cancelApply(Integer transId) {
        AssemblyTransSheet flowTrans = assemblyMapper.getTransSheet(transId);
        AssemblyRoute flowRoute = assemblyMapper.findCurRoute(flowTrans);
        flowRoute.setApplyNum(flowTrans.getNum());
        int res = assemblyMapper.updateRouteApplyToCancelApply(flowRoute);
        //删除转序单
        res += assemblyMapper.updateTransIsdel(transId, 1);
        // 如果没申请质检，转序状态设置成未开始
        res += assemblyMapper.updateRouteStatusNotStarted(flowRoute.getId());
        return res;
    }

    /**
     * 删除质检申请
     */
    @Transactional(rollbackFor = Exception.class)
    public int delApply(Integer id) {
        AssemblyTransSheet trans = assemblyMapper.getTransSheet(id);
        if (trans.getIsDel() == 1) {
            return 0;
        }
        assemblyMapper.updateTransIsdel(id, 1);
        AssemblyRoute route = assemblyMapper.findCurRoute(trans);
        route.setApplyNum(trans.getNum());
        return assemblyMapper.updateRouteDel(route);
    }

    /**
     * 重新申请质检
     */
    public int repeatApply(Integer id) {
        return assemblyMapper.updateTransStatus(id, 1);
    }


    /**
     * 二维码解析
     */
    private QrParse getQrParse(String code) {
        String[] arr = code.split("\\|");
        if (arr == null || arr.length < 4) {
            return null;
        }
        QrParse parse = new QrParse();
        parse.setProNo(arr[0]);
        parse.setDrawNo(arr[1]);
        parse.setPartId(arr[2]);
        parse.setCategory(arr[3]);
        return parse;
    }

    /**
     * 根据主键获取对应的路线
     */
    public AssemblyRoute getAssemblyRouteByPrimaryKey(Integer routeId) {
        return assemblyMapper.getAssemblyRouteByPrimaryKey(routeId);
    }

    /**
     * 质检合格
     */
    @Transactional(rollbackFor = Exception.class)
    public int success(FlowTrans trans) {
//        AssemblyTransSheet t = assemblyMapper.getTransSheet(trans.getId());
//        AssemblyTransCheck tc = assemblyMapper.getTransSheetCheck(trans.getId());
//        if (tc.getStatus() != 1) {
//            return 0;
//        }
//        User u = (User) ServletUtils.getSession().getAttribute("user");
//        tc.setCheckCode(u.getAccount());
//        tc.setCheckName(u.getName());
//        tc.setCheckTime(new Date());
//        if (u.getBranch() != null) {
//            tc.setCheckDept(u.getBranch());
//        }
//        tc.setYield(trans.getYield() == null ? 0 : 1);
//        tc.setResult(trans.getResult());
//        tc.setStatus(2);
//
//        AssemblyRoute cur = assemblyMapper.findCurRoute(t);
//        AssemblyRoute next = assemblyMapper.findNextRoute(cur);
//        AssemblySheet sheet = assemblyMapper.getSheet(cur);
//        int totalNum = sheet.getDrawNum() - sheet.getInvalid();
//        cur.setCheckNum(cur.getCheckNum() + t.getNum());
//        if (totalNum == cur.getCheckNum().intValue()) {
//            cur.setStatus(4);
//        } else {
//            cur.setStatus(3);
//        }
//        if ("转储".equals(next.getRoute())) {
//            //修改倒数第二道序为已接收
//            tc.setStatus(3);
//            //修改最后一道序的接收数量和状态
//            next.setRecNum(next.getRecNum() + t.getNum());
//            if (next.getRecNum() == totalNum) {
//                next.setStatus(4);
//            } else {
//                next.setStatus(3);
//            }
//            assemblyMapper.updateRouteRecNum(next);
//
//            // 判断 库存记录是否已经存在，存在更新，不存在插入（保证装配派工单与）
//            AssemblyStore asseStore = assemblyMapper.findStoreBySheetId(sheet.getId());
//            AssemblyStore store = new AssemblyStore();
//            // 插入成品库
//            if (asseStore != null) {
//                BeanUtil.copy(asseStore, store);
//                store.setSheetId(sheet.getId());
//                store.setDrawNum(asseStore.getDrawNum() + t.getNum());
//                store.setStoreAddr(t.getApplyDept());
//                assemblyMapper.updateStore(store);
//            } else {
//                BeanUtil.copy(sheet, store);
//                store.setSheetId(sheet.getId());
//                store.setDrawNum(t.getNum());
//                store.setStoreAddr(t.getApplyDept());
//                store.setId(null);
//                assemblyMapper.insertStore(store);
//            }
//
//            // 生产装配件入库记录
//            AssemblyStoreRecord storeRecord = new AssemblyStoreRecord();
//            storeRecord.setProdNo(store.getProdNo());
//            storeRecord.setSpecial(store.getSpecial());
//            storeRecord.setPartId(store.getPartId());
//            storeRecord.setDrawName(store.getDrawName());
//            storeRecord.setDrawNo(store.getDrawNo());
//            storeRecord.setWeight(store.getDrawWeight());
//            storeRecord.setDrawNum(t.getNum());
//            storeRecord.setStoreType(1);
//            storeRecord.setRecordType(1);
//            storeRecord.setStoreAddr(store.getStoreAddr());
//            storeRecord.setStorageRegisterCode(t.getApplyCode());
//            storeRecord.setStorageTime(new Date());
//            storeRecord.setCheckOpinion(tc.getResult());
//            storeRecord.setRemark(null);
//            storeRecord.setReplaceId(null);
//            storeRecord.setAsseStoreId(store.getId());
//            assemblyMapper.insertStoreRecord(storeRecord);
//            // 转序单记录出入库记录主键，冲单时使用
//            t.setRecordId(storeRecord.getId());
//            assemblyMapper.updateSheetTrans(t);
//        }
//        cur.setRouteDate(new Date());// 最终转序时间
//        assemblyMapper.updateRouteCheck(cur);
//        assemblyMapper.updateCheckTrans(tc);
//
//        /**20210608 会议讨论 会议人员：徐一贺、陈欣、李青雨、马超、王松刚
//         * 1.如果生产令下所有工艺卡都已经装配完成时，回写生产令任务装配状态为已完成
//         * 2.如果生产令下生产、装配、安装任务都完成时，回写生产令生产完成状态及完成时间
//         * **/
//        if ("转储".equals(next.getRoute()) && next.getStatus().compareTo(4) == 0) {
//            // 取得机械和流体未完成工艺卡装配数
//            int jlCount = assemblyMapper.getJxLtNotTranCompCount(sheet.getProdNo(), sheet.getId());
//            if (jlCount == 0) {
//                // 更新生产令装配任务状态
//                ProdTasStatus prodTas = new ProdTasStatus();
//                prodTas.setProdNo(sheet.getProdNo());
//                prodTas.setProtSta(3);//任务状态：1=未开始，2=执行中，3=已完成
//                prodTas.setProtDat(new Date());// 状态反写时间
//                prodTas.setProtDepId(u.getBranchId());// 状态反写部门
//                prodTas.setProtEndDat(new Date());// 结束时间
//                assemblyMapper.updateProdTasProtStaByProdNo(prodTas);
//                // 更新生产令生产完成状态及时间
//                udpCodStaAndDate(sheet.getProdNo(), 2);
//            } else {
//                // 更新生产令装配任务开始时间及状态
//                ProdTasStatus prodTas = new ProdTasStatus();
//                prodTas.setProdNo(sheet.getProdNo());
//                prodTas.setProtSta(2);//任务状态：1=未开始，2=执行中，3=已完成
//                prodTas.setProtDat(new Date());// 状态反写时间
//                prodTas.setProtDepId(u.getBranchId());// 状态反写部门
//                prodTas.setProtStaDat(new Date());// 开始时间
//                assemblyMapper.updateProdTasStartProtStaByProdNo(prodTas);
//            }
//        } else {
//            // 更新生产令装配任务开始时间及状态
//            ProdTasStatus prodTas = new ProdTasStatus();
//            prodTas.setProdNo(sheet.getProdNo());
//            prodTas.setProtSta(2);//任务状态：1=未开始，2=执行中，3=已完成
//            prodTas.setProtDat(new Date());// 状态反写时间
//            prodTas.setProtDepId(u.getBranchId());// 状态反写部门
//            prodTas.setProtStaDat(new Date());// 开始时间
//            assemblyMapper.updateProdTasStartProtStaByProdNo(prodTas);
//        }
        return 1;
    }

    /**
     * 质检驳回
     */
    @Transactional(rollbackFor = Exception.class)
    public int reject(FlowTrans trans) {
//        AssemblyTransSheet t = assemblyMapper.getTransSheet(trans.getId());
//        AssemblyTransCheck tc = assemblyMapper.getTransSheetCheck(trans.getId());
//        if (tc.getStatus() != 1) {
//            return 0;
//        }
//        User u = (User) ServletUtils.getSession().getAttribute("user");
//        tc.setCheckCode(u.getAccount());
//        tc.setCheckName(u.getName());
//        tc.setCheckTime(new Date());
//        if (u.getBranch() != null) {
//            tc.setCheckDept(u.getBranch());
//        }
//        tc.setStatus(trans.getStatus() == null ? 4 : 5);
//        tc.setReason((trans.getReason() == null || trans.getReason().length() < 1) ? "质检不合格，驳回" : trans.getReason());
//        // 如果作废， sheet表添加作废数量
//        if (tc.getStatus() == 5) {
//            AssemblyRoute cur = assemblyMapper.findCurRoute(t);
//            AssemblySheet sheet = assemblyMapper.getSheet(cur);
//            sheet.setInvalid(sheet.getInvalid() + t.getNum());
//            assemblyMapper.updateSheetInvalid(sheet);
//        }
//        return assemblyMapper.updateRejectTrans(tc);
        return 1;
    }

    /**
     * 历史质检
     */
    public List<AssemblyModel> findHisCheckList() {
        User u = (User) ServletUtils.getSession().getAttribute("user");
        return assemblyMapper.findHisCheckList(u.getAccount());
    }

    /**
     * 取消质检
     */
    public int cancelCheck(Integer transId) {
        AssemblyTransSheet t = assemblyMapper.getTransSheet(transId);
        AssemblyTransCheck tc = assemblyMapper.getTransSheetCheck(transId);

        AssemblyRoute cur = assemblyMapper.findCurRoute(t);
        AssemblySheet sheet = assemblyMapper.getSheet(cur);
        AssemblyRoute next = assemblyMapper.findNextRoute(cur);

        // 注：领导说暂无报废功能
        if (tc.getStatus() == 1 || tc.getStatus() == 4 || tc.getStatus() == 5) {
            return 0;
        }
        if (tc.getStatus() == 3 && !next.getRoute().equals("转储")) {
            return 0;
        }

        // 回写 装配质检表
        tc.setCheckCode(null);
        tc.setCheckName(null);
        tc.setCheckTime(null);
        tc.setCheckDept(null);
        tc.setReason(null);
        tc.setResult(null);
        tc.setYield(0);
        tc.setStatus(1);
        t.setRecordId(null);

        // 回写 工序审核数量
        cur.setCheckNum(cur.getCheckNum() - t.getNum());
        cur.setStatus(2); // 工序执行中
        assemblyMapper.updateRouteCheck(cur);
        assemblyMapper.updateCheckTrans(tc);
        assemblyMapper.updateSheetTrans(t);

        // 判断 是否是最后工序，如果最后工序‘转储’时，要删除 asse_store 成品库 数据
        if ("转储".equals(next.getRoute())) {
            next.setRecNum(0);
            next.setStatus(1);
            assemblyMapper.updateRouteRecNum(next);

            AssemblyStore asseStore = assemblyMapper.findStoreBySheetId(sheet.getId());
            AssemblyStoreRecord storeRecordP = assemblyMapper.findStoreRecordById(t.getRecordId());

            // 修改成品库对应数据
            assemblyMapper.udpAsseStoreBySheetId(asseStore);

            // 生产装配件入库记录(冲单)
            AssemblyStoreRecord storeRecordM = new AssemblyStoreRecord();
            BeanUtil.copy(storeRecordP, storeRecordM);
            storeRecordM.setStoreType(1);
            storeRecordM.setRecordType(2);
            storeRecordM.setStorageTime(new Date());
            storeRecordM.setReplaceId(storeRecordP.getId());
            storeRecordM.setId(null);
            assemblyMapper.insertStoreRecord(storeRecordM);
        }
        return 1;
    }

    /**
     * 接收
     */
    @Transactional(rollbackFor = Exception.class)
    public int rec(FlowTrans trans) {
        AssemblyTransSheet t = assemblyMapper.getTransSheet(trans.getId());
        AssemblyTransCheck tc = assemblyMapper.getTransSheetCheck(trans.getId());
        if (tc.getStatus() != 2) {
            return 0;
        }

        User u = (User) ServletUtils.getSession().getAttribute("user");
        t.setRecCode(u.getAccount());
        t.setRecName(u.getName());
        t.setRecTime(new Date());
        t.setRecDept(u.getBranch());
        tc.setStatus(3);
        assemblyMapper.updateRecSheetTrans(t);
        assemblyMapper.updateCheckTrans(tc);

        AssemblyRoute cur = assemblyMapper.findCurRoute(t);
        //获取下一道序
        AssemblyRoute next = assemblyMapper.findNextRoute(cur);
        next.setRecNum(next.getRecNum() + t.getNum());
        next.setMayApplyNum(next.getMayApplyNum() + t.getNum());
        next.setStatus(2);
        return assemblyMapper.updateRouteRecNum(next);
    }

    /**
     * 历史接收
     */
    public List<AssemblyModel> findHisRecList() {
        User u = (User) ServletUtils.getSession().getAttribute("user");
        return assemblyMapper.findHisRecList(u.getAccount());
    }

    /**
     * 取消接收
     */
    @Transactional(rollbackFor = Exception.class)
    public int cancelRec(FlowTrans trans) {
        AssemblyTransSheet t = assemblyMapper.getTransSheet(trans.getId());
        AssemblyTransCheck tc = assemblyMapper.getTransSheetCheck(trans.getId());
        if (tc.getStatus() != 3) {
            return 0;
        }

        t.setRecCode(null);
        t.setRecName(null);
        t.setRecTime(null);
        t.setRecDept(null);
        tc.setStatus(2);
        assemblyMapper.updateRecSheetTrans(t);
        assemblyMapper.updateCheckTrans(tc);

        AssemblyRoute cur = assemblyMapper.findCurRoute(t);
        //获取下一道序
        AssemblyRoute next = assemblyMapper.findNextRoute(cur);
        next.setRecNum(next.getRecNum() - t.getNum());
        next.setMayApplyNum(next.getMayApplyNum() - t.getNum());
        next.setStatus(1);
        return assemblyMapper.updateRouteRecNum(next);
    }

    /**
     * @param prodNo 生产令编号
     * @param type   调用源头：1=生产，2=装配，3=安装
     * @Author wsg
     * @Date 13:29 2021/6/8
     * @Description 更新生产令生产完成状态及时间
     **/
    public Integer udpCodStaAndDate(String prodNo, Integer type) {

        Integer status = 0;// 0=未完成，1=已完成
        Date comDat = null;// 完成时间
        ProdTasStatus tasStatus = assemblyMapper.getProdTasStatusByProdNo(prodNo);
        if (type.compareTo(1) == 0 && tasStatus != null
                && (tasStatus.getAssSta().compareTo(3) == 0 || tasStatus.getAssSta().compareTo(0) == 0)
                && (tasStatus.getInsSta().compareTo(3) == 0 || tasStatus.getInsSta().compareTo(0) == 0)) {
            // 生产
            status = 1;
            comDat = new Date();
        } else if (type.compareTo(2) == 0 && tasStatus != null
                && (tasStatus.getProdSta().compareTo(3) == 0 || tasStatus.getProdSta().compareTo(0) == 0)
                && (tasStatus.getInsSta().compareTo(3) == 0 || tasStatus.getInsSta().compareTo(0) == 0)) {
            // 装配
            status = 1;
            comDat = new Date();
        } else if (type.compareTo(3) == 0 && tasStatus != null
                && (tasStatus.getProdSta().compareTo(3) == 0 || tasStatus.getProdSta().compareTo(0) == 0)
                && (tasStatus.getAssSta().compareTo(3) == 0 || tasStatus.getAssSta().compareTo(0) == 0)) {
            // 安装
            status = 1;
            comDat = new Date();
        }
        return assemblyMapper.udpCodStaAndDate(prodNo, status, comDat);
    }

}
